//
//  ZWLSqureView.swift
//  ZWLDY
//
//  Created by czh on 2016/10/12.
//  Copyright © 2016年 zwl. All rights reserved.
//

import UIKit

private let squreViewID = "squreViewID"

class ZWLSqureView: UIView {
    
    var groups : [AnchorGroup]? {
        didSet {
            collectionview.reloadData()
        }
    }
    
    
    @IBOutlet weak var page: UIPageControl!
    @IBOutlet weak var collectionview: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        
        collectionview.register(UINib(nibName: "ZWLSqrureCell", bundle: nil), forCellWithReuseIdentifier: squreViewID)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let layout = collectionview.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionview.bounds.size
    }

}

extension ZWLSqureView : UICollectionViewDelegate,UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if groups == nil { return 0 }
        let pageNum = (groups!.count - 1) / 8 + 1
        page.numberOfPages = pageNum
        
        return pageNum
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: squreViewID, for: indexPath) as! ZWLSqrureCell
        
        setupCellDataWithCell(cell: cell, indexPath: indexPath)
        return cell
    }
    
    
    private func setupCellDataWithCell(cell : ZWLSqrureCell, indexPath : IndexPath) {
        // 0页: 0 ~ 7
        // 1页: 8 ~ 15
        // 2也: 16 ~ 23
        // 1.取出起始位置&终点位置
        let startIndex = indexPath.item * 8
        var endIndex = (indexPath.item + 1) * 8 - 1
        
        // 2.判断越界问题
        if endIndex > groups!.count - 1 {
            endIndex = groups!.count - 1
        }
        
        // 3.取出数据,并且赋值给cell
        cell.groups = Array(groups![startIndex...endIndex])
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        page.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
    }
}

extension ZWLSqureView {
     class func squreView() -> ZWLSqureView {
        
        return Bundle.main.loadNibNamed("ZWLSqureView", owner: nil, options: nil)?.last as! ZWLSqureView
    }
    
}
